import React, { useState } from "react";
import ProForm, { ProFormText, ProFormTextArea } from "@ant-design/pro-form";
import MusicAPI from '@/services/ant-design-pro/music';
import { Modal, message } from 'antd'
const { addMusicLyric, updateMusicLyric } = MusicAPI
const CreateOrEdit = (props) => {
    const { isModalVisible, isShowModal, actionRef, setData, initData } = props;
    const type = initData === undefined ? "添加" : "编辑";

    /**
     * 添加或编辑歌词
     * @param {obj} params 参数
     * @returns 
     */
    const handleSubmit = async (params) => {
        let result;
        if (initData === undefined) { // 添加
            result = await addMusicLyric(params);
        } else { // 编辑
            let i = 0;
            for (let key in params) {
                if (params[key] == initData[key]) {
                    i++;
                }
            }
            if (i >= 1)
                return message.error("您还未修改数据")

            result = await updateMusicLyric({
                ...initData,
                ...params,
            });
        }

        if (result.status == 'ok') {
            await setData();
            actionRef.current.reload();
            message.success(type + "成功");
        } else {
            message.error(type + '失败：' + result.data.message);
            console.log(result.data.error);
        }
        isShowModal(false);
    }

    return (
        <Modal
            width="600px"
            title={`${type}歌词`}
            footer={false}
            visible={isModalVisible}
            onCancel={() => isShowModal(false)}
            destroyOnClose={true}>
            {
                <ProForm
                    onFinish={(values) => handleSubmit(values)}
                    initialValues={initData}
                >
                    {
                        initData === undefined ? (
                            <ProFormText
                                name="lyric_name"
                                label="歌词名称"
                                placeholder="请输入名称"
                                rules={[
                                    { required: true, message: "请输入名称" }
                                ]}
                            />
                        ) : (
                            <h3>{initData.music_name}</h3>
                        )
                    }

                    <ProFormTextArea width="xl" label="歌词" name="lyric"
                        rules={[
                            { required: true, message: "请输入歌词" }
                        ]} />
                </ProForm>
            }
        </Modal>
    );
}

export default CreateOrEdit;